package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.AttrEntity;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SpuAttrValueEntity;
import com.atguigu.gmall.pms.mapper.AttrMapper;
import com.atguigu.gmall.pms.mapper.SkuAttrValueMapper;
import com.atguigu.gmall.pms.mapper.SpuAttrValueMapper;
import com.atguigu.gmall.pms.vo.AttrValueVo;
import com.atguigu.gmall.pms.vo.ItemGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.AttrGroupMapper;
import com.atguigu.gmall.pms.entity.AttrGroupEntity;
import com.atguigu.gmall.pms.service.AttrGroupService;
import org.springframework.util.CollectionUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupMapper, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrMapper attrMapper;

    @Autowired
    private SpuAttrValueMapper spuAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<AttrGroupEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public List<AttrGroupEntity> queryGroupsWithAttrsByCid(Long cid) {
        // 1.根据分类id查询分组
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("category_id", cid));
        if (CollectionUtils.isEmpty(attrGroupEntities)){
            return attrGroupEntities;
        }

        // 2.遍历分组查询组下的规格参数
        attrGroupEntities.forEach(attrGroupEntity -> {
            List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>().eq("group_id", attrGroupEntity.getId()).eq("type", 1));
            attrGroupEntity.setAttrEntities(attrEntities);
        });
        return attrGroupEntities;
    }

    @Override
    public List<ItemGroupVo> queryGroupsWithAttrValuesByCidAndSpuIdAndSkuId(Long cid, Long spuId, Long skuId) {
        // 1.根据cid查询分组
        List<AttrGroupEntity> groupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("category_id", cid));
        if (CollectionUtils.isEmpty(groupEntities)){
            return null;
        }

        // 2.遍历分组查询每一组下的规格参数
        return groupEntities.stream().map(attrGroupEntity -> {
            ItemGroupVo itemGroupVo = new ItemGroupVo();
            itemGroupVo.setId(attrGroupEntity.getId());
            itemGroupVo.setName(attrGroupEntity.getName());

            // 查询组下的规格参数
            List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>().eq("group_id", attrGroupEntity.getId()));
            if (CollectionUtils.isEmpty(attrEntities)){
                return itemGroupVo;
            }

            // 把规格参数entity集合 转化成 AttrValueVo集合
            itemGroupVo.setAttrValues(attrEntities.stream().map(attrEntity -> {
                AttrValueVo attrValueVo = new AttrValueVo();

                attrValueVo.setAttrId(attrEntity.getId());
                attrValueVo.setAttrName(attrEntity.getName());

                // 如果type是1则从pms_spu_attr_value表中查询值；如果type是0则重pms_sku_attr_value表中查询值
                if (attrEntity.getType() == 1) {
                    SpuAttrValueEntity spuAttrValueEntity = this.spuAttrValueMapper.selectOne(new QueryWrapper<SpuAttrValueEntity>().eq("spu_id", spuId).eq("attr_id", attrEntity.getId()));
                    attrValueVo.setAttrValue(spuAttrValueEntity.getAttrValue());
                } else {
                    SkuAttrValueEntity skuAttrValueEntity = this.skuAttrValueMapper.selectOne(new QueryWrapper<SkuAttrValueEntity>().eq("sku_id", skuId).eq("attr_id", attrEntity.getId()));
                    attrValueVo.setAttrValue(skuAttrValueEntity.getAttrValue());
                }

                return attrValueVo;
            }).collect(Collectors.toList()));
            return itemGroupVo;
        }).collect(Collectors.toList());
    }

    public static void main(String[] args) throws IOException {
//        FutureTask<String> futureTask = new FutureTask<>(() -> {
//            System.out.println("1这是Callable方式初始化多线程程序！");
//            return "hello Callable...";
//        });
//        new Thread(futureTask).start();
//
//        while (!futureTask.isDone()) {
//            System.out.println("子任务还没有执行完。。。");
//        }
//        try {
//            // 阻塞方式获取到子任务的返回结果集
//            System.out.println("2子任务的返回结果集：" + futureTask.get());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        ExecutorService executorService = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
//        executorService.execute(() -> {
//            System.out.println("1这是线程池方式初始化子线程");
//        });
//        CompletableFuture.runAsync(() -> {
//            System.out.println("1这是通过CompletableFuture.runAsync初始化了一个多线程任务！");
//        });

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("1这是通过CompletableFuture.supplyAsync初始化了一个多线程任务！");
            //int i = 1/0;
            return "hello CompletableFuture";
        });
        CompletableFuture<String> future1 = future.thenApplyAsync(t -> {
            System.out.println("=================thenApplyAsync====================");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("上一个任务的返回结果：" + t);
            return "hello thenApplyAsync";
        });
        CompletableFuture<Void> future2 = future.thenAcceptAsync(t -> {
            System.out.println("=================thenAcceptAsync====================");
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("上一个任务的返回结果：" + t);
        });
        CompletableFuture<Void> future3 = future.thenRunAsync(() -> {
            System.out.println("=================thenRunAsync====================");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("不获取上一个任务的结果，也没有自己的返回结果集");
        });

        CompletableFuture.anyOf(future1, future2, future3).join();
//                .whenCompleteAsync((t, u) -> {
//            System.out.println("2===============whenCompleteAsync===================");
//            System.out.println("上一个任务的返回结果集t: " + t);
//            System.out.println("上一个任务的异常信息u: " + u);
//        }).exceptionally(t -> {
//            System.out.println("3=================exceptionally=======================");
//            System.out.println("t: " + t);
//            return "hello exceptionally";
//        });

        System.out.println("4这是main线程");
        System.in.read();
    }
}
